const formRules = require("../util/formRules.js");
module.exports = {
	/**
	 * 修改角色
	 * @url admin/system/role/sys/update 前端调用的url参数地址
	 * data 请求参数 说明
	 * @param {String} _id
	 * @param {Boolean} integrals
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		// 业务逻辑开始----------------------------------------------------------- 
		let {
				_id,
				scores,
				comments,
				record_flag
			} = data;
		// 参数合法校验开始-----------------------------------------------------------
		let formRulesRes = await formRules.update(event);
		if (formRulesRes.code !== 0) {
			return formRulesRes;
		}
		// 参数合法校验结束-----------------------------------------------------------
		// 创建回滚
		const transaction = await vk.baseDao.startTransaction();
		try {
			if(scores){
				// 用户扣除积分
				if(isNaN(scores) && parseFloat(scores) == 0){
					return {
						code: -1,
						msg: "积分输入错误"
					}
				}
				scores = parseFloat(scores)
				// 执行数据库API请求
				var user = await vk.baseDao.updateAndReturn({
					db:transaction,
					dbName: "uni-id-users",
					whereJson:{
						_id: _id,
						score : _.gte(scores*-1)
					},
					dataJson: {
						score: _.inc(scores)
					}
				});
				if(!user){
					return {
						code: -1,
						msg:"积分不足"
					}
				}
				if(record_flag === 1){
					// 增加用户收益记录
					let record_id = await vk.baseDao.add({
						db:transaction,
						dbName: "uni-id-scores",
						dataJson: {
							user_id: _id,
							type: scores>0?1:2,
							score: scores>0?scores:-scores,
							balance: user.score,
							comment: comments
						}
					});
					if(!record_id){
						await transaction.rollback();
						return {
							code: -1,
							msg:"积分记录更新失败"
						}
					}
				}
				// 提交事物
				await transaction.commit();
			}
		}catch (err) {
			// 事务回滚
			await transaction.rollback();
			console.error(`transaction error`, err)
			return {
				code: -1,
				msg:"数据库写入异常,事务已回滚",
				err: {
					message:err.message,
					stack:err.stack
				}
			}
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}

}